package promote.brozen.base.thread;

import promote.brozen.utils.concurrent.Threads;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * 调用带有超时时间的sleep\object.wait\thread.join\LockSupport.park会使线程进入TIMED_WAITING状态
 *
 * @author Brozen
 * @date 2020/9/10 5:59 PM
 * @email brozen@qq.com
 */
public class ThreadTimedWaiting {

    private static final Object MONITOR = new Object();

    public static void main(String[] args) {
        Thread sleepThread = new Thread(() -> {
            Threads.silentSleep(100000L);
        });

        Thread waitThread = new Thread(() -> {
            synchronized (MONITOR) {
                try {
                    MONITOR.wait(TimeUnit.HOURS.toMillis(1));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread joinThread = new Thread(() -> {
            try {
                sleepThread.join(TimeUnit.HOURS.toMillis(1));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread parkThread = new Thread(() -> {
            LockSupport.parkNanos(TimeUnit.HOURS.toNanos(1));
        });

        sleepThread.start();
        waitThread.start();
        joinThread.start();
        parkThread.start();

        Threads.silentSleep(100L);

        System.out.println("SleepThread = " + sleepThread.getState());
        System.out.println("WaitThread = " + waitThread.getState());
        System.out.println("JoinThread = " + joinThread.getState());
        System.out.println("ParkThread = " + parkThread.getState());
    }

}
